home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1148 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  69 lines

  1. Path: news.iag.net!news
  2. From: jatmon@iag.net (John R Buchan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Trouble with file return code.
  5. Date: 11 Jan 1996 17:27:02 GMT
  6. Organization: Internet Access Group, Orlando, Florida
  7. Message-ID: <4d3h96$9fl@news.iag.net>
  8. References: <tcpnntpd.16.1.10.20.22.42.2781597121.333610@the-fix.sos.on.ca>
  9. NNTP-Posting-Host: pm3-orl4.iag.net
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <tcpnntpd.16.1.10.20.22.42.2781597121.333610@the-fix.sos.on.ca>, 
  13. xenon@the-fix.sos.on.ca says...
  14. >
  15. >       Im having some trouble getting fread to return NULL when it can't
  16. >find a specific file...
  17. >
  18. >         else if((ptr=fread(filename1,"rb"))!=NULL)
  19. >  {
  20. >       //do this }
  21. >         else    {
  22. >       // do that
  23. >       // this never executes, even if NULL is returned.
  24. >No matter the file, Null is never returned.  Although, when the variable
  25. >ptr is outputed, the value shown is "0".
  26.  
  27. ?? No ansi compiler will even compile this code.  So, how could you possible
  28. determine that NULL is not being returned?  The prototype for fread is:
  29.  
  30.    size_t fread( void *ptr, size_t size, size_t nobj, FILE *stream);
  31.  
  32. fread returns the number of objects read, not a pointer. Try this:
  33.  
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36.  
  37. int main(void)
  38.    {
  39.    FILE *ptr;
  40.    char filename[] = "tmp.dat";
  41.    char buf[20];
  42.       
  43.    if ((ptr = fopen(filename, "rb")) == NULL)
  44.       {
  45.       fprintf(stderr, "Cannot open file.\n");
  46.       exit( EXIT_FAILURE);
  47.       }
  48.       
  49.    /* Of course, you'll want to do better i/o testing, but basically */
  50.    while( fread(buf, sizeof(buf), 1, ptr) == 1)
  51.       {
  52.       /* play with the data */
  53.       }
  54.       
  55.    fclose(ptr);
  56.    return 0;
  57.    }
  58.  
  59. BTW, you should try to post a minimum complete compilable example that 
  60. produces your error.  You should also d/l and read through the c.l.c faq
  61. (Frequently Asked Question) list. It contains answers for many of the 
  62. common gotcha's in c programming.  It is available for anonymous ftp from
  63. rtfm.mit.edu /pub/usenet/comp.lang.c.
  64.  
  65. -- 
  66. John R Buchan           -:|:-     Looking for that elusive FAQ?  ftp to:
  67. jatmon@mail.iag.net     -:|:-     rtfm.mit.edu /pub/usenet-by-group/....
  68.  
  69.